﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Visualization.DataModel
{
    public partial class CSVProcessingGUI : Form
    {
        DataProcessor processor = new DataProcessor();
        int completedBgOperations = 0;
        public CSVProcessingGUI()
        {
            InitializeComponent();
            processor.worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            processor.worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            processor.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            completedBgOperations++;
            if (!(e.Error == null))
                MessageBox.Show("An error occurred");
            else if (completedBgOperations % 3 == 2)
                processor.worker.RunWorkerAsync("WriteData");
            else if (completedBgOperations % 3 == 1)
                processor.worker.RunWorkerAsync("ProcessParticles");
            else if (completedBgOperations % 3 == 0)
                textBox1.Text = "Complete!";
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = e.UserState.ToString();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument.Equals("ReadCSV"))
                processor.retrieveCSVData(textBox1.Text);
            if (e.Argument.Equals("ProcessParticles"))
                processor.processParticles();
            if (e.Argument.Equals("WriteData"))
                processor.writeProcessedData(textBox1.Text.Substring(0, textBox1.Text.LastIndexOf('.'))+".xml");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result.Equals(DialogResult.OK))
                textBox1.Text = openFileDialog1.FileName;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            processor.worker.RunWorkerAsync("ReadCSV");
        }
    }
}
